package com.wondertek.poms.core.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wondertek.poms.core.config.UrlConfig;
import com.wondertek.poms.dao.po.MoveContLog;
import com.wondertek.poms.dao.po.PrdCont;
import com.wondertek.poms.dao.po.SysDictData;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * <b>SystemSettingUtil Description:</b> 系统配置调用接口
 * </p>
 *
 * @author douzi <b>DATE</b> 2019年7月16日 上午11:07:18
 */
@Slf4j
@Component
public class OutHttpUtil {

    @Autowired
    private UrlConfig urlConfig;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RestTemplate restTemplateOut;

    /**
     * bc:true 需要播控，false 不需要播控.
     *
     * @since JDK 1.8
     */
    /*@Value("${oes.bc.need}")
    private Boolean bc;*/

    /**
     * <p><b>Title:</b> findByKey</p>
     * <p><b>Description:</b> 通过ckey获取系统配置值/p>
     *
     * @param ckey
     * @return
     * @author douzi
     */
    public String findByKey(String ckey) {
        ResponseEntity<String> responseEntity = restTemplate
                .getForEntity(urlConfig.getSystemConfigUrl() + "?ckey=" + ckey, String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONObject result = jsonObject.getJSONObject("result");
        String value = null;
        if (result != null && !result.isEmpty()) {
            value = result.getString("value");
        }
        log.info("ckey:" + ckey + "|value:" + value);
        return value;
    }

    /**
     * <p><b>Title:</b> findByType</p>
     * <p><b>Description:</b> 根据类型获取字典集合</p>
     *
     * @param type
     * @return
     * @author douzi
     */
    public List<SysDictData> findByType(String type) {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlConfig.getDictUrl() + "?type=" + type,
                String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray result = jsonObject.getJSONArray("result");
        List<SysDictData> list = new ArrayList<>();
        JSONObject object = null;
        if (result != null && !result.isEmpty()) {
            for (int i = 0; i < result.size(); i++) {
                SysDictData dict = new SysDictData();
                object = result.getJSONObject(i);
                String value = object.getString("value");
                String label = object.getString("label");
                dict.setValue(value);
                dict.setLabel(label);
                dict.setType(type);
                list.add(dict);
            }
        }
        return list;
    }

    /**
     * <p><b>Title:</b> findMoveLog</p>
     * <p><b>Description:</b> 调用移包log</p>
     *
     * @param contentId
     * @param id
     * @param isIn
     * @return
     * @author douzi
     */
    public MoveContLog findMoveLog(String contentId, Long id, boolean isIn) {
        String url = urlConfig.getMovePrdInfoUrl();
        if (isIn) {
            url = url + "?contentId=" + contentId + "&secondPrdInfoPackage=" + id;
        } else {
            url = url + "?contentId=" + contentId + "&oldPrdInfoId=" + id;
        }
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONObject result = jsonObject.getJSONObject("result");
        MoveContLog movePrdInfoLog = JSON.toJavaObject(result, MoveContLog.class);
        return movePrdInfoLog;
    }

    /**
     * <p><b>Title:</b> bcSend</p>
     * <p><b>Description:</b> 同步播控系统</p>
     *
     * @return
     * @author douzi
     */
    /*public String bcSend(BcSendVo osdpVo) {
        // 跳过播控注释20191023
        if (bc) {
            HttpEntity<BcSendVo> httpEntity = new HttpEntity<>(osdpVo);
            ResponseEntity<String> postForEntity = restTemplate.postForEntity(urlConfig.getSyncBcUrl(), httpEntity,
                    String.class);
            return getCode(postForEntity);
        }
        return "";
    }*/

    /**
     * <p><b>Title:</b> bcSend</p>
     * <p><b>Description:</b> 同步播控系统</p>
     *
     * @return
     * @author douzi
     */
//    public String delbcRecord(Long prdContId) {
//        if (bc) {
//            log.info(prdContId + "媒资下线需通知播控删除播控池得数据防止复用");
//            restTemplate.delete(urlConfig.getDelBcrecordUrl() + "?prdContId={prdContId}", prdContId);
//            return "sucess";
//        }
//        return "";
//    }

    /**
     * <p><b>Title:</b> bcSend</p>
     * <p><b>Description:</b> 同步搜索引擎系统</p>
     *
     * @return
     * @author douzi
     */
    public String esOnlineSend(String json) {
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(urlConfig.getSyncEsUrl(), json,
                String.class);
        return getCode(responseEntity);
    }

    /**
     * 搜索引擎搜索接口
     *
     * @param json 搜索条件
     * @return 搜索数据
     */
    public String esSearch(String json) {

        HttpHeaders headers = new HttpHeaders();
        // 定义请求参数类型，这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> request = new HttpEntity<>(json, headers);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(
                // urlConfig.getEsSearch(),
                // "192.168.1.74:8098/es/assets/search",
                "http://oes-search-service/es/assets/search",
                // http://oes-es
                request, String.class);

        return responseEntity.getBody();
    }
    
    /**
     * <p><b>Title:</b> bcSend</p>
     * <p><b>Description:</b> 节目调用poms上线</p>
     *
     * @return
     * @author douzi
     */
    public String online(PrdCont pc) {
//    	ResponseEntity<String> responseEntity = restTemplateOut
//                .getForEntity(urlConfig.getOnlineUrl()+ "?prdContIds=" + pc.getPrdContId(), String.class);
//    	String body = responseEntity.getBody();
    	
    	String requestGet = HttpClientUtil.requestGet(urlConfig.getOnlineUrl()+ "?prdContIds=" + pc.getPrdContId());
    	log.info("上线流程|内容对象：" + pc.getContentId() + "|上线节目:" + pc.getPrdContId() + "|返回值为:" + requestGet);
    	return requestGet;
    }
    
    /**
     * <p><b>Title:</b> bcSend</p>
     * <p><b>Description:</b> 节目调用poms下线</p>
     *
     * @return
     * @author douzi
     */
    public String offline(PrdCont pc, String model) {
//    	ResponseEntity<String> responseEntity = restTemplateOut
//                .getForEntity(urlConfig.getOfflineUrl() + "?prdContIds=" + pc.getPrdContId(), String.class);
//    	String body = responseEntity.getBody();
    	String requestGet = HttpClientUtil.requestGet(urlConfig.getOfflineUrl()+ "?prdContIds=" + pc.getPrdContId());
    	log.info(model + "|内容对象：" + pc.getContentId() + "|下线节目:" + pc.getPrdContId() + "|返回值为:" + requestGet);
    	return requestGet;
    }

    /**
     * <p><b>Title:</b> getCode</p>
     * <p><b>Description:</b> 返回码解析</p>
     *
     * @param responseEntity
     * @return
     * @author douzi
     */
    private static String getCode(ResponseEntity<String> responseEntity) {
        String response = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(response);
        String code = jsonObject.getString("code");
        return code;
    }

    /**
     * <p>
     * <b>Title:</b> 获取版权CP列表
     * </p>
     * <p>
     * <b>Description:</b> 调用版权CP列表接口
     * </p>
     *
     * @return
     * @author anyouz
     */
    public Map<String, String> getAllCpForExport() {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlConfig.getAllCpUrl(),
                String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray result = jsonObject.getJSONArray("result");
        JSONObject object = null;
        Map<String, String> map = new HashMap<>();
        if (result != null && !result.isEmpty()) {
            for (int i = 0; i < result.size(); i++) {
                object = result.getJSONObject(i);
                String cpId = object.getString("cpId");
                String cpName = object.getString("cpName");
                map.put(cpId, cpName);
            }
        }
        return map;
    }

    /**
     * 获取cp的map，以便于商品包规则导入
     * @author anyouz
     * @return
     */
    public Map<String, Long> getAllCpForImport() {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlConfig.getAllCpUrl(),
                String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray result = jsonObject.getJSONArray("result");
        JSONObject object = null;
        Map<String, Long> map = new HashMap<>();
        if (result != null && !result.isEmpty()) {
            for (int i = 0; i < result.size(); i++) {
                object = result.getJSONObject(i);
                Long cpId = object.getLong("cpId");
                String cpName = object.getString("cpName");
                map.put(cpName,cpId);
            }
        }
        return map;
    }

    /**
     * <p><b>Title:</b> getAllFirstClassify</p>
     * <p><b>Description:</b> 导入时，获取内容系统一级分类</p>
     *
     * @return
     * @author anyouz
     */
    public Map<String,String> getAllFirstClassifyForImport() {
        //enumCode=first_class_code ,itemType=3 时是一级分类
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlConfig.getFirstClassifyDictUrl()+"?enumCode=first_class_code&itemType=3", String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray result = jsonObject.getJSONArray("result");
        Map<String, String> map = new HashMap<>();
        JSONObject object = null;
        if (result != null && !result.isEmpty()) {
            for (int i = 0; i < result.size(); i++) {
                object = result.getJSONObject(i);
                String label = object.getString("itemName");
                String itemCode = object.getString("itemCode");
                map.put(label, itemCode);
            }
        }
        return map;
    }

    /**
     * <p><b>Title:</b> getAllFirstClassifyForExport</p>
     * <p><b>Description:</b> 导出时，获取内容系统一级分类</p>
     *
     * @return
     * @author anyouz
     */

    public Map<String,String> getAllFirstClassifyForExport() {
        //enumCode=first_class_code ,itemType=3 时是一级分类
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlConfig.getFirstClassifyDictUrl()+"?enumCode=first_class_code&itemType=3", String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray result = jsonObject.getJSONArray("result");
        Map<String, String> map = new HashMap<>();
        JSONObject object = null;
        if (result != null && !result.isEmpty()) {
            for (int i = 0; i < result.size(); i++) {
                object = result.getJSONObject(i);
                String itemCode = object.getString("itemCode");
                String label = object.getString("itemName");
                map.put(itemCode, label);
            }
        }
        return map;
    }

    /**
     * <p><b>Title:</b> getAllProductionPlatformForExport</p>
     * <p><b>Description:</b> 导出时，获取内容系统生产平台</p>
     *
     * @return
     * @author anyouz
     */
    public Map<String,String> getAllProductionPlatformForImport(){
        //enumCode=enumCode ,itemType=2 时是生产平台
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlConfig.getFirstClassifyDictUrl()+"?enumCode=production_platform_code&itemType=2", String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray result = jsonObject.getJSONArray("result");
        Map<String, String> map = new HashMap<>();
        JSONObject object = null;
        if (result != null && !result.isEmpty()) {
            for (int i = 0; i < result.size(); i++) {
                object = result.getJSONObject(i);
                String label = object.getString("itemName");
                String itemCode = object.getString("itemCode");
                map.put(label, itemCode);
            }
        }
        return map;
    }

    /**
     * <p><b>Title:</b> findContentLabel</p>
     * <p><b>Description:</b> 调取内容标签</p>
     *
     * @param itemType
     * @return
     * @author huzhenjie
     */
    public List<SysDictData> findContentLabel(String itemType) {

        ResponseEntity<String> responseEntity = restTemplate
                .getForEntity("http://oes-content-label/redis/list-enum-values?enumCode=" + itemType,
                        String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray result = jsonObject.getJSONArray("result");
//        List<SysDictData> list = new ArrayList();
        List<SysDictData> list = new ArrayList<>();
        JSONObject object;
        if (!result.isEmpty()) {
            for (int i = 0; i < result.size(); i++) {
                SysDictData dict = new SysDictData();
                object = result.getJSONObject(i);
                String value = object.getString("itemCode");
                String label = object.getString("itemName");
                dict.setValue(value);
                dict.setLabel(label);
                list.add(dict);
            }
        }
        return list;
    }

    /**
     * http://180.167.180.242:8009/oes-content-configuration/configuration/mam-attr-enum/get-all?attrId=45
     *
     * @param itemType
     * @return
     */
    public List<SysDictData> findContentConfig(String itemType) {
        ResponseEntity<String> responseEntity = restTemplate
                .getForEntity("http://oes-content-configuration/configuration/mam-attr-enum/get-all?attrId=" + itemType,
                        String.class);
        String json = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(json);
        String resultStr = jsonObject.getString("result");
        JSONObject jsonObjectEnumVoListStr = JSONObject.parseObject(resultStr);
        String jsonObjectEnumVoListStrList = jsonObjectEnumVoListStr.getString("enumVoList");

        JSONArray result = JSONObject.parseArray(jsonObjectEnumVoListStrList);
//        JSONArray result = jsonObject.getJSONArray("result");
//        List<SysDictData> list = new ArrayList();
        List<SysDictData> list = new ArrayList<>();
        JSONObject object;
        if (!result.isEmpty()) {
            for (int i = 0; i < result.size(); i++) {
                SysDictData dict = new SysDictData();
                object = result.getJSONObject(i);
                String value = object.getString("id");
                String label = object.getString("attrValue");
                dict.setValue(value);
                dict.setLabel(label);
                list.add(dict);
            }
        }
        return list;
    }

}
